package com.hmall.common.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
//@ConfigurationProperties(prefix = "spring.application")
//@ConditionalOnClass(value = {MessageConverter.class, RabbitTemplate.class})
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
public class MqConsumeErrorAutoConfiguration {

    @Value("${spring.application.name}")
    private String name;

    @Bean
    public Queue errorQueue() {
        return new Queue(name + ".error.queue", true);
    }

    @Bean
    public DirectExchange errorExchange() {
        return ExchangeBuilder.directExchange("error.direct")
                .durable(true).build();
    }

    @Bean
    public Binding errorQueueBinding() {
        return BindingBuilder.bind(errorQueue()).to(errorExchange()).with(name);
    }

//    失败后将消息投递到一个指定的，专门存放异常消息的队列，后续由人工集中处理。
    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, "error.direct", name);
    }
}
